package com.zy.activity.stock;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import zy.entity.base.bra.T_Base_Bra;
import zy.entity.base.color.T_Base_Color;
import zy.entity.base.size.T_Base_Size;
import zy.entity.shop.sale.T_Shop_Sale;
import zy.entity.stock.data.T_Stock_DataView;
import zy.util.StringUtil;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.zy.R;
import com.zy.activity.BaseActivity;
import com.zy.adapter.stock.InfoAdapter;
import com.zy.api.stock.StockAPI;
import com.zy.util.ActivityUtil;
import com.zy.util.Constants;
import com.zy.view.view.AutoListView.OnLoadListener;
import com.zy.view.view.RadioGroupView;

public class StockInfoActivity extends BaseActivity implements OnLoadListener,OnClickListener{
	private ImageView img_back;
	private Handler handler;
	private TextView txt_title,tv_pd_name,tv_sd_amount,tv_pd_price;
	private RadioGroupView rgv_color,rgv_size;
	private CheckBox cb_other;
	private LinearLayout ll_depot;
	private String cr_code = "",pd_code = "",sz_code = "",dp_code = "";
	private StockAPI stockAPI;
	private InfoAdapter infoAdapter;
	private ListView listView;
	private Map<String,Object> stockMap = new HashMap<String, Object>();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_stockinfo);
		initView();
		initListener();
		initHandler();
		loadData();
	}
	private void initView(){
		txt_title = (TextView)findViewById(R.id.txt_title);
		txt_title.setText(getIntent().getStringExtra(Constants.TITLE));
		img_back = (ImageView) findViewById(R.id.img_back);
		img_back.setVisibility(View.VISIBLE);
		tv_pd_name = (TextView) findViewById(R.id.tv_pd_name);
		tv_sd_amount = (TextView) findViewById(R.id.tv_sd_amount);
		tv_pd_price = (TextView) findViewById(R.id.tv_pd_price);
		rgv_color = (RadioGroupView) findViewById(R.id.rgv_color);
		rgv_size = (RadioGroupView) findViewById(R.id.rgv_size);
		cb_other = (CheckBox) findViewById(R.id.cb_other);
		ll_depot = (LinearLayout) findViewById(R.id.ll_depot);
		pd_code = this.getIntent().getStringExtra("pd_code");// 获取货号
		listView = (ListView) findViewById(R.id.lv_data);
		stockAPI = new StockAPI(this);
		infoAdapter = new InfoAdapter(this);
		listView.setAdapter(infoAdapter);
	}
	private void initListener(){
		img_back.setOnClickListener(this);
		cb_other.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(null != sz_code && !"".equals(sz_code)){
					if (cb_other.isChecked()){
						ll_depot.setVisibility(View.VISIBLE);
						otherStock();
					}else{
						ll_depot.setVisibility(View.GONE);
					}
				}else{
					ActivityUtil.showShortToast(StockInfoActivity.this, "请选择尺码");
				}
			}
		});
	}
	private void initHandler(){
		handler = new Handler() {
			@SuppressWarnings("unchecked")
			public void handleMessage(Message msg) {
				switch (msg.what) {
					case STATE_LOAD:{
						if(msg.obj == null){
							return;
						}
						Map<String,Object> result = (Map<String,Object>) msg.obj;
						if(null != result){
							stockMap =result;
							initData();
						}
		                break;
					}
					case STATE_SAVE:
						if(msg.obj == null){
							return;
						}
						List<T_Stock_DataView> list = (List<T_Stock_DataView>)msg.obj;
						infoAdapter.setStocks(list);
						infoAdapter.notifyDataSetChanged();
						break;
					case STATE_ERROR:
						String message = null;
						if(msg.obj != null){
							message = msg.obj.toString();
						}
						ActivityUtil.showShortToast(StockInfoActivity.this, message);
						break;
				}
				super.handleMessage(msg);
			}
		};
	}
	private void setRadioStyle(RadioButton btn){
		btn.setTextColor(Color.BLACK);
		btn.setButtonDrawable(android.R.color.transparent);
		btn.setBackgroundResource(R.drawable.radio_bg);
		btn.setPadding(25, 15, 25, 15);
	}
	@SuppressWarnings("unchecked")
	private void initData(){
		T_Stock_DataView data = (T_Stock_DataView)stockMap.get("stock");
		if(null != data){
			tv_pd_name.setText("商品："+data.getPd_no()+"/"+data.getPd_name());
			tv_sd_amount.setText("库存："+data.getSd_amount());
			tv_pd_price.setText("价格："+data.getPd_sell_price());
			dp_code = data.getSd_dp_code();
		}
		List<T_Base_Color> colorList = (List<T_Base_Color>)stockMap.get("color");
		if(null != colorList && colorList.size() > 0){
			int index = 0;
			cr_code = colorList.get(0).getCr_code();
			for(T_Base_Color color:colorList){
				int amount = getColorStock(color.getCr_code());
				RadioButton btn = initColor(color.getCr_name(), color.getCr_code(), amount);
				if(index == 0){
					btn.performClick();
				}
				index ++;
			}
		}
	}
	@SuppressWarnings("unchecked")
	private int getColorStock(String code){
		int amount = 0;
		List<T_Stock_DataView> stocks = (List<T_Stock_DataView>)stockMap.get("stocks");
		for (T_Stock_DataView stock:stocks) {
			if (stock.getSd_code().startsWith(pd_code+code)){
				amount += stock.getSd_amount();
			}
		}
		return amount;
	}
	private RadioButton initColor(final String name,final String code,final int amount){
		RadioButton btn = new RadioButton(rgv_color.getContext());
		setRadioStyle(btn);
		btn.setText(name+"["+amount+"]");
		btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				changeColor(code);
			}
		});
		rgv_color.addView(btn);
		return btn;
	}
	/**
	 * 选择颜色
	 */
	private void changeColor(String code){
		cr_code = code;
		initSize();
	}
	@SuppressWarnings("unchecked")
	private int getSizeStock(String sizeCode){
		List<T_Stock_DataView> stocks = (List<T_Stock_DataView>)stockMap.get("stocks");
		String subCode = pd_code + StringUtil.trimString(cr_code)+StringUtil.trimString(sizeCode);
		for (T_Stock_DataView data:stocks) {
			if (subCode.equals(data.getSd_code())){
				return data.getSd_amount();
			}
		}
		return 0;
	}
	private RadioButton addSizeControl(final String text,final String value){
		RadioButton btn = new RadioButton(rgv_size.getContext());
		setRadioStyle(btn);
		btn.setText(text);		
		btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				changeSize(value);
			}
		});
		rgv_size.addView(btn);
		return btn;
	}
	public void changeSize(String code){
		sz_code = code;
		otherStock();
	}
	
	private void otherStock(){
		if (cb_other.isChecked()){
			if(null != sz_code && !"".equals(sz_code)){
				loadOtherStock();
			}else{
				ActivityUtil.showShortToast(StockInfoActivity.this, "请选择尺码");
			}
		}
	}
	private void flush(){
		infoAdapter.setStocks(new ArrayList<T_Stock_DataView>());
		infoAdapter.notifyDataSetChanged();
	}
	@SuppressWarnings("unchecked")
	private void initSize(){
		rgv_size.removeAllViews();
		flush();
		List<T_Base_Size> sizes = (List<T_Base_Size>)stockMap.get("size");
		List<T_Base_Bra> bras = (List<T_Base_Bra>)stockMap.get("bra");
		for (T_Base_Size size:sizes) {
			if(null != bras && bras.size() > 0){
				for(T_Base_Bra bra:bras){
					int index = 0;
					int stock = getSizeStock(size.getSz_code()+bra.getBr_code());
					if (stock == 0){
						continue;
					}
					String text=String.valueOf(size.getSz_name()+"/"+bra.getBr_name()+"["+stock+"]");
					RadioButton btn = addSizeControl(text,size.getSz_code()+bra.getBr_code());
					if(index == 0){
						btn.performClick();
					}
					index ++;
				}
			}else{
				int index = 0;
				int stock = getSizeStock(size.getSz_code());
				if (stock == 0){
					continue;
				}
				String text=String.valueOf(size.getSz_name()+"["+stock+"]");
				RadioButton btn = addSizeControl(text,size.getSz_code());
				if(index == 0){
					btn.performClick();
				}
				index ++;
			}
		}
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img_back:
			ActivityUtil.finish(StockInfoActivity.this);
			break;

		default:
			break;
		}
	}
	private void loadOtherStock(){
		Map<String, Object> paramMap = buildBaseParam();
		paramMap.put("sub_code", pd_code+cr_code+sz_code);
		paramMap.put("dp_code", dp_code);
		stockAPI.otherStock(paramMap, handler, STATE_SAVE);
	}
	private void loadData(){
		Map<String, Object> paramMap = buildBaseParam();
		paramMap.put("pd_code", pd_code);
		stockAPI.queryStock(paramMap, handler, STATE_LOAD);
	}
	@Override
	public void onLoad() {
		loadData();
	}
	
}
